#include "xplay.h"
#include <QFileDialog>
#include "xFFmpeg.h"
#include "XAudioPlay.h"
#include "QToolButton"
#include "XVideoThread.h"


#define PAUSE "QToolButton:!hover{border-image: url(:/xplay/Resources/play_hot.png);} \
QToolButton:hover{ border-image: url(:/xplay/Resources/play_normal.png); }"

#define PLAY "QToolButton:!hover{border-image: url(:/xplay/Resources/pause_hot.png);} \
QToolButton:hover{ border-image: url(:/xplay/Resources/pause_normal.png); }"
static bool isPlay = false;

xplay::xplay(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	startTimer(40);
	connect(ui.btnopen, &QToolButton::clicked, this, &xplay::open);
	connect(ui.btnplay, &QToolButton::clicked, this, &xplay::play);
	connect(ui.playSlider, &QSlider::sliderPressed, this, &xplay::sliderPress);
	connect(ui.playSlider, &QSlider::sliderReleased, this, &xplay::sliderRelease);


}

void xplay::resizeEvent(QResizeEvent *event)
{
	ui.openGLWidget->resize(size());

}

void xplay::timerEvent(QTimerEvent *event)
{
	 
	if (xFFmpeg::Get()->Totalms > 0)
	{
		float rate = (float)xFFmpeg::Get()->pts / (float)xFFmpeg::Get()->Totalms;
		if (!isPressSlider)
			ui.playSlider->setValue(rate * ui.playSlider->maximum());
	}
}

void xplay::sliderPress()
{
	isPressSlider = true;
}

void xplay::sliderRelease()
{
	isPressSlider = false;
	float pos = 0;
	pos = (float)ui.playSlider->value() / (float)(ui.playSlider->maximum() + 1);
	XVideoThread::Get()->clearbuf();
	xFFmpeg::Get()->Seek(pos);
}

void xplay::open()
{
	isPlay = false;
	QString path = QFileDialog::getOpenFileName(this, "open video file", ".", "*.*");
	if (path.isEmpty())
		return;
	
	xFFmpeg::Get()->isPlay = false;
	XVideoThread::Get()->exitPlay();
	XVideoThread::Get()->wait();
	
	
	if (xFFmpeg::Get()->Open(path.toLocal8Bit()) == false)
	{
		this->setWindowTitle("ERROR:"+path);
		return;
	}
	this->setWindowTitle(path); 
	
	
	XAudioPlay::Get()->sampleRate = xFFmpeg::Get()->sampleRate;
	XAudioPlay::Get()->channel = xFFmpeg::Get()->channel;
	XAudioPlay::Get()->sampleSize = 16;
	XAudioPlay::Get()->Start();

	play();
	XVideoThread::Get()->start();
}

void xplay::play()
{
	isPlay = !isPlay;
	xFFmpeg::Get()->isPlay = isPlay;
	if (isPlay)
	{
		//ui.btnplay->setStyleSheet(PAUSE);
	}
	else
	{

		//ui.btnplay->setStyleSheet(PLAY);
	}
}

